﻿#!/usr/bin/env pwsh
#Requires -version 5

# usage: (in powershell)
#  Invoke-Expression (Invoke-Webrequest <my location> -UseBasicParsing).Content
Write-Host "如果上面有报错，不用管"

# 搜索注册表中的Steam安装路径
$SteamPath = (Get-ItemProperty -Path "HKLM:\SOFTWARE\WOW6432Node\Valve\Steam" -Name "InstallPath" | Select-Object -ExpandProperty "InstallPath")
if ([string]::IsNullOrEmpty($SteamPath)) {
    Write-Host "找不到Steam安装路径"
    return
}

# 打开steamapps\libraryfolders.vdf文件
$LibraryFoldersVDFPath = Join-Path $SteamPath "steamapps\libraryfolders.vdf"
if (!(Test-Path $LibraryFoldersVDFPath)) {
    Write-Host "没有安装Steam"
    return
}

# 提取文件中的多个path
$LibraryFolders = (Get-Content $LibraryFoldersVDFPath | Select-String -Pattern "path" | ForEach-Object { $_.ToString().Split('"')[3].Trim() })

ForEach ($LibraryFolder in $LibraryFolders) {

    # 打开游戏的appmanifest文件
    $AppManifestPath = Join-Path $LibraryFolder "steamapps\appmanifest_1422450.acf"
    if (Test-Path -Path $AppManifestPath -PathType leaf) {
        break
    }
    else {
        $AppManifestPath = $null
    }
}

if ([string]::IsNullOrEmpty($AppManifestPath)) {
    Write-Host "没有安装Deadlock"
    return
}

# 提取AppState中的installdir
$Installdir = (Get-Content $AppManifestPath | Select-String -Pattern "installdir" | ForEach-Object { $_.ToString().Split('"')[3].Trim() })
if ([string]::IsNullOrEmpty($Installdir)) {
    Write-Host "无法提取installdir"
    return
}

# 组合安装路径
$InstallDir = Join-Path $LibraryFolder "steamapps\common\" | Join-Path -ChildPath $Installdir

Write-Host "安装路径："$InstallDir

# 下载文件
$DownloadURL = "https://github.com/233Isaac/DeadlockSC/archive/refs/heads/main.zip"
$DownloadFile = Join-Path $env:TEMP "DeadlockSC.zip"
$ExpandArchiveFolder = Join-Path $env:TEMP "DeadlockSC"

$StatusCode = 404
for ($RetryCount = 0; $RetryCount -lt 3; $RetryCount++) {
    Write-Host "正在下载文件..."

    try {
        $Response = Invoke-WebRequest -Uri $DownloadURL -OutFile $DownloadFile
        $StatusCode = 200
    } catch {
        $StatusCode = 404
    }

    if ($StatusCode -ne 200) {
        if ($RetryCount -lt 3) {
            Write-Host "下载失败，正在重试..."
        }
    }
    else {
        break
    }
}

if ($StatusCode -ne 200) {
    Write-Host "下载失败，请检查网络连接并重试"
    return
}

Write-Host "下载成功"

try {
    # 将下载完成后的文件解压缩到临时目录
    Expand-Archive -Path $DownloadFile -DestinationPath $ExpandArchiveFolder -Force

    Write-Host "解压缩文件成功"

    try {
        # 将解压缩后的txt文件，移动覆盖到$InstallDir里
        $DestinationDir = $InstallDir

        Write-Host "正在移动文件..."

        Join-Path $ExpandArchiveFolder "DeadlockSC-main" | Get-ChildItem -Filter "game" | Move-Item -Destination $DestinationDir -Force

        Write-Host "移动文件成功"
    }
    finally {
        # 删除临时文件夹
        Remove-Item -Path $ExpandArchiveFolder -Recurse
    }
}
finally {
    # 删除下载文件
    Remove-Item -Path $DownloadFile
}